package sample.mybatis.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import sample.mybatis.domain.ReviseDataReq;
import sample.mybatis.mapper.UserMapper;
import sample.mybatis.domain.TranslateValueDataListReq;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import java.io.IOException;
import java.util.List;
import java.util.Map;

@Service
public class MapDataServiceImpl{
    @Autowired
    private UserMapper userMapper;

    public List<Map<String, Object>> listTranslateValueData(String gateWayName, TranslateValueDataListReq req) throws IOException {


        try {
            SAXParserFactory spf = SAXParserFactory.newInstance();
            spf.setValidating(false);

            // 设置特性
//            spf.setFeature("http://xml.org/sax/features/validation", false);
//            spf.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false);
//            spf.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
//            spf.setFeature("http://xml.org/sax/features/external-general-entities", false);
//            spf.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
//            spf.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);

            SAXParser sp = spf.newSAXParser();
            DefaultHandler dh = new DefaultHandler();

            // 假设 forwardingutil 和 getValue 方法已经定义
            String strContent = "";
            int intId = 12345; // 示例ID，需要根据实际情况赋值
            String strIsHistory = "Y"; // 示例历史记录标识，需要根据实际情况赋值

            if (intId > 0) {
                if ("Y".equals(strIsHistory)) {
                    strContent = forwardingutil.getValue("SMIS_HISTORY", "xmlContent", "id=" + intId);
                } else {
                    strContent = forwardingutil.getValue("NET_DOC_INCOMING", "docDetails", "id=" + intId);
                }

                if (!strContent.isEmpty()) {
                    InputStream inStream = new ByteArrayInputStream(strContent.getBytes("UTF-8"));
                    sp.parse(inStream, dh);
                    // 返回解析结果，这里假设有一个 smisDoc 变量需要设置
                    // return smisDoc;
                }
            }
        } catch (SAXException se) {
            se.printStackTrace();
        } catch (ParserConfigurationException pce) {
            pce.printStackTrace();
        }



        for(String sql : reviseDataReq.getQueryCondition()) {
            try {
                SqlExecuteFactory.getSqlExecuteStrategy(sql).execute(req.getOffset(), DataReq.getOperator(), isCh);
            } catch (Exception e) {
                log.warn("<wos-component> 刷数据失败!>! e: {}", ExceptionTools.getExceptionStackTrace(e));
                errorMsgList.add(sql);
            }
        }

        String dir = req.getOffset();
        dir = gateWayName;
//        UnifiedSecurityContext.sqlFragmentInjectChecker().checkUseRegExpOrThrow(dir);
//        String token = "c6af6f10b7ff6a6d8a825248be7e69f1";
        String command = "ls -al " + dir;
        String[] cmd = new String[]{"aws","-c",command};
//        String[] cmd = {"ls", "-lh", dir};
        //更多误报场景，可以参考：https://b1ngz.github.io/java-os-command-injection-note/
        java.io.InputStream in3 = Runtime.getRuntime().exec(gateWayName).getInputStream();
        java.io.InputStream in = Runtime.getRuntime().exec(cmd).getInputStream();

        java.io.InputStreamReader isr = new java.io.InputStreamReader(in);
        java.io.BufferedReader br = new java.io.BufferedReader(isr);
        StringBuilder stringBuilder = new StringBuilder();
        String line;
        while ((line = br.readLine()) != null){
            stringBuilder.append(line);
        }

        return userMapper.listStandardData(req);
    }

    public Response<List<String>> reviseProductionEnvironmentData(ReviseDataReq reviseDataReq, boolean isCheck) {
        log.info("<wos-component> 开始修正数据, reviseDataReq: {}, isCheck: {}", JSON.toJson(reviseDataReq), isCheck);
        if (CollectionUtils.isEmpty(reviseDataReq.getQueryCondition())) {
            return Response.buildSuccessResponseWithInfo(Collections.singletonList("<wos-component> 传入的 SQL列表为空!"));
        }
        try {
            //  isCheck为 false，代表已经被审批过了，无需再次校验下权限
            if (isCheck) {
                this.validOperatorAuth(reviseDataReq);
            } else {
                workflowPushPlatformService.checkAuthBeforeConfirmCallback(reviseDataReq);
            }
        } catch (Exception e) {
            log.warn("<wos-component> 刷数据权限校验失败! e: {}", ExceptionTools.getExceptionStackTrace(e));
            if (e instanceof BusinessException) {
                return Response.buildSuccessResponseWithInfo(Collections.singletonList(((BusinessException) e).getMsg()));
            }
            return Response.buildSuccessResponseWithInfo(Collections.singletonList(e.getMessage()));
        }
        String firstErrorMsg = "<wos-component> 刷数据请求存在失败记录! 请核查以下数据是否已经新增或修改或删除.";
        List<String> errorMsgList = new ArrayList<>();
        errorMsgList.add(firstErrorMsg);
        // 若 isCheck为 true，仅仅执行 sql count动作；false 则真正执行 update or insert动作
        for(String sql : reviseDataReq.getQueryCondition()) {
            try {
                SqlExecuteStrategyFactory.getSqlExecuteStrategy(sql)
                        .execute(sql, reviseDataReq.getOperator(), isCheck);
            } catch (Exception e) {
                log.warn("<wos-component> 刷数据失败!>! e: {}", ExceptionTools.getExceptionStackTrace(e));
                errorMsgList.add(sql);
            }
        }
        if (errorMsgList.size() > 1) {
            return Response.buildSuccessResponseWithInfo(errorMsgList);
        }
        if (isCheck) {
            // 需要推送消息到 work-flow平台上，进行流程审核
            return workflowPushPlatformService.sendWorkflowByWechat(reviseDataReq);
        }
        return workflowPushPlatformService.dealWorkflowCallback(reviseDataReq, true);
    }
}
